import numpy as np

data =np.array([[12, 15, 13, 28, 24],
          [7, 11, 10, 19, 21],
          [12, 14, 11, 27, 23],
          [6, 7, 4, 13, 20],
          [13, 14, 13, 27, 25]])

def distance(x,y):
    return np.sqrt(np.sum((x-y)**2))

#分成几类
K=3

oldcenters=0
centers = data[0:K]

print(centers)
groupList=[0,0,0,0,0]

length = data.shape[0]

while(1):
# 算出距离并且去距离最小的作为自己的组
    for i in range(length):
        minDis = 100000
        for j in range(K):
            if distance(data[i],centers[j])<minDis:
                minDis = distance(data[i],centers[j])
                groupList[i] = j

    print(groupList)

    oldcenters = centers.copy()

    #重新计算中心点
    for i in range(K):
        count = 0
        temp = np.array([[1.0,1.0,1.0,1.0,1.0]])
        for j in range(len(groupList)):
            if i == groupList[j]:
                count+=1
                temp = np.vstack((temp,data[j]))
        temp = temp[1:]
        print(temp)
        print(np.mean(temp,axis=0))
        centers[i]=np.mean(temp,axis=0)

    print(centers)
    print(oldcenters)

    chazhi = 0
    for i in range(K):
        chazhi += distance(centers[i],oldcenters[i])
    if chazhi <0.001:
        print(chazhi)
        break

print(groupList)